<?php
namespace app\lib\token;

use think\facade\Request;

class UserToken {

    /**
     * 授予用户token
     *
     * @param $user
     * @return void
     */
    public static function grant($user){
        // 组织存放的数据
        $vars['uid'] = $user->id;
        $vars['role'] = $user->role;
        $vars['username'] = $user->username;
        // ...
        return (new Token())->set($vars); // 此处应该用单例模式调用
    }

    public static function getFromHttp(){
        $token = Request::instance()->header('Authorization');
        return empty($token) ? false : $token;
    }

    /**
     * 获取用户token信息
     *
     * @param string $field
     * @return array|false|string
     */
    public static function getValues(string $field = ''){
        $token = self::getFromHttp();
        if (! $token) return false;
        return (new Token($token))->get($field);
    }

    /**
     * 保持活性
     *
     * @return string
     */
    public static function keepActive(){
        $token = self::getFromHttp();
        $tokenOj = new Token($token);
        $grantTime = $tokenOj->get('exp_time');
        if (! $grantTime) return false;
        $retime = $grantTime - time();
        if ($retime < 60) {
            // 过期时间5分钟内活跃，则续命30分钟
            $token = $tokenOj->alive(1800);
        }
        return $token;
    }

}
